using net_work.Config;
using net_work.Data.DTO.Hmw;
using net_work.Data.Entity.Hmw;
using net_work.Data.Enum.Hmw;
using net_work.IRepository.Hmw;

namespace net_work.Repository.Hmw;

public class HomeworkRepository(ApplicationDbContext dbContext)
    : Repository<Homework>(dbContext), IHomeworkRepository
{
    public async Task<long> InsertAsync(HomeworkAddRequest homeworkAddRequest)
    {
        var newHomework = new Homework
        {
            Remark = homeworkAddRequest.Remark,
            Title = homeworkAddRequest.Title,
            Description = homeworkAddRequest.Description,
            BeginTime = homeworkAddRequest.BeginTime,
            Deadline = homeworkAddRequest.Deadline,
            AllowMultiple = homeworkAddRequest.AllowMultiple,
            Status = HomeworkStatus.UnRelease,
            TeachId = homeworkAddRequest.TeachId
        };
        await dbContext.Homeworks.AddAsync(newHomework);
        await dbContext.SaveChangesAsync();
        return newHomework.Id;
    }

    public async Task<bool> UpdateAsync(HomeworkUpdateRequest homeworkUpdateRequest)
    {
        var homework = await dbContext.Homeworks.FindAsync(homeworkUpdateRequest.Id);
        if (homework == null)
        {
            return false;
        }

        homework.Remark = homeworkUpdateRequest.Remark;
        homework.Title = homeworkUpdateRequest.Title;
        homework.Description = homeworkUpdateRequest.Description;
        homework.BeginTime = homeworkUpdateRequest.BeginTime;
        homework.Deadline = homeworkUpdateRequest.Deadline;
        homework.AllowMultiple = homeworkUpdateRequest.AllowMultiple;
        homework.TeachId = homeworkUpdateRequest.TeachId;

        await dbContext.SaveChangesAsync();
        return true;
    }

    public async Task<bool> Release(long homeworkId)
    {
        var homework = await dbContext.Homeworks.FindAsync(homeworkId);
        if (homework == null)
        {
            return false;
        }

        homework.Status = HomeworkStatus.Release;
        homework.ReleaseDateTime = DateTime.Now.ToLocalTime();
        return await dbContext.SaveChangesAsync() > 0;
    }
}